package flc.ast.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;

import com.banshengyanyu.bottomtrackviewlib.TrackModel;
import com.banshengyanyu.bottomtrackviewlib.interfaces.ClipVideoListener;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.stark.ve.EditorHolder;
import com.stark.ve.core.IEditorListener;

import java.util.List;

import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.databinding.ActivityAudioExtractBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.media.audio.AudioFormat;
import stark.common.basic.media.audio.AudioPlayerImpl;
import stark.common.basic.media.audio.IAudioPlayer;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.TimeUtil;

public class AudioExtractActivity extends BaseAc<ActivityAudioExtractBinding> implements ClipVideoListener {

    public static String videoPath;
    private String cutPath;
    private String outPath = "";
    protected IAudioPlayer mAudioPlayer;
    private long videoLength;
    private long tailorStartTime;
    private long tailorEndTime;

    private Handler mHandler;
    private final Runnable mTaskUpdateTime = new Runnable() {
        @Override
        public void run() {
            mDataBinding.tvPlayLeft.setText(TimeUtil.getMmss(mDataBinding.videoView.getCurrentPosition()));
            mHandler.postDelayed(this, 500);
        }
    };

    @Override
    protected int onCreate() {
        return R.layout.activity_audio_extract;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);

        mDataBinding.ivAudioExtractBack.setOnClickListener(v -> onBackPressed());
        mDataBinding.ivPlayStart.setOnClickListener(this);
        mDataBinding.ivPlayFull.setOnClickListener(this);
        mDataBinding.ivPlay.setOnClickListener(this);
        mDataBinding.ivAudioExtractSave.setOnClickListener(this);
        mAudioPlayer = new AudioPlayerImpl();
        mAudioPlayer.setListener(new IAudioPlayer.IListener() {
            @Override
            public void onUpdatePlayTime(int curPlayTime, int duration) {
                mDataBinding.tvPlayLeftText.setText(TimeUtil.getMmss(curPlayTime));
                mDataBinding.tvPlayRightText.setText("/" + TimeUtil.getMmss(duration));
                mDataBinding.trackView.setPlayTime(curPlayTime);
                mDataBinding.trackView.setDuration(duration);
            }

            @Override
            public void onPlayChange(boolean isPlaying) {
                if (isPlaying) {
                    mDataBinding.ivPlay.setImageResource(R.drawable.abofzhong);
                } else {
                    mDataBinding.ivPlay.setImageResource(R.drawable.azantinz);
                }
            }
        });
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivPlayStart://视频播放
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.abofang);
                    mDataBinding.videoView.pause();
                } else {
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.azant);
                    mDataBinding.videoView.start();
                    startTime();
                }
                break;
            case R.id.ivPlayFull://放大
                PlayActivity.videoUri = videoPath;
                startActivity(PlayActivity.class);
                break;
            case R.id.ivPlay://播放
                if (mAudioPlayer.isPlaying()) {
                    mAudioPlayer.pause();
                } else {
                    mAudioPlayer.resume();
                }
                break;
            case R.id.ivAudioExtractSave://保存
                saveVideo();
                break;
        }
    }

    @Override
    protected void initData() {
        videoLength = MediaUtil.getDuration(videoPath);
        cutPath = videoPath;
        //设置播放器
        setPlayer();
        audioExt();
        //设置剪切功能
        mDataBinding.bottomTrackView.setClipVideoMode(TrackModel.ClipVideoMode.OPERATION);
        mDataBinding.bottomTrackView.setMode(TrackModel.ClipMode.CLIP);
        mDataBinding.bottomTrackView.initInfo(videoPath, videoLength, true,
                0, videoLength, 1.0f);
        mDataBinding.bottomTrackView.setClipVideoListener(this);
        mDataBinding.bottomTrackView.setVisibility(View.GONE);
    }


    //设置播放器
    private void setPlayer() {
        mHandler = new Handler();
        mDataBinding.tvPlayLeft.setText("00:00");
        mDataBinding.tvPlayRight.setText(" / " + TimeUtil.getMmss(videoLength));
        mDataBinding.videoView.setVideoPath(videoPath);
        mDataBinding.videoView.seekTo(1);
        mDataBinding.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                mDataBinding.tvPlayLeft.setText("00:00");
                mDataBinding.ivPlayStart.setImageResource(R.drawable.abofang);
                mDataBinding.videoView.seekTo(1);
                stopTime();
            }
        });
        //直接播放视频
        mDataBinding.videoView.seekTo(1);
        mDataBinding.ivPlayStart.setImageResource(R.drawable.azant);
        mDataBinding.videoView.start();
        startTime();
    }

    private void audioExt() {
        List<AudioFormat> audioFormats = EditorHolder.editor().supportAudioFormat();
        EditorHolder.editor().videoExtractAudio(cutPath, audioFormats.get(0), new IEditorListener() {
            @Override
            public void onSuccess(String outFilePath) {
                dismissDialog();
                ToastUtils.showShort(getString(R.string.extract_suc));
                outPath = outFilePath;
                mAudioPlayer.play(outPath);
            }

            @Override
            public void onFailure(String errMsg) {
                dismissDialog();
                ToastUtils.showShort(R.string.extract_def);
            }

            @Override
            public void onProgress(int progress) {
                showDialog(getString(R.string.extract_ing) + progress + getString(R.string.unit_percent));
            }
        });
    }

    //剪切视频
    private void cutVideo() {
        if (tailorEndTime == 0 && tailorStartTime == 0) {
            ToastUtils.showShort(R.string.cut_tip);
        } else {
            EditorHolder.editor().videoCut(videoPath, tailorStartTime, tailorEndTime, new IEditorListener() {
                @Override
                public void onSuccess(String outFilePath) {
                    dismissDialog();
                    cutPath = outFilePath;
//                    videoLength = MediaUtil.getDuration(cutPath);
//                    mDataBinding.tvPlayLeft.setText("00:00");
//                    mDataBinding.tvPlayRight.setText(" / " + TimeUtil.getMmss(videoLength));
//                    //直接播放视频
//                    mDataBinding.videoView.setVideoPath(cutPath);
//                    mDataBinding.videoView.seekTo(1);
//                    mDataBinding.ivPlayStart.setImageResource(R.drawable.azant);
//                    mDataBinding.videoView.start();
//                    startTime();
                    audioExt();
                    ToastUtils.showShort(R.string.cut_suc);
                }

                @Override
                public void onFailure(String errMsg) {
                    dismissDialog();
                    ToastUtils.showShort(R.string.cut_def);
                }

                @Override
                public void onProgress(int progress) {
                    showDialog(getString(R.string.corp_ing) + progress + "%");
                }
            });
        }
    }

    //保存视频
    private void saveVideo() {
        showDialog(getString(R.string.saving));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        FileP2pUtil.copyPrivateAudioToPublic(mContext, outPath);
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        dismissDialog();
                        ToastUtils.showShort(R.string.save_success);
                        startActivity(HomeActivity.class);
                    }
                });
            }
        }, 1000);
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopTime();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //直接播放视频
        mDataBinding.videoView.seekTo(1);
        mDataBinding.ivPlayStart.setImageResource(R.drawable.azant);
        mDataBinding.videoView.start();
        startTime();
    }

    private void startTime() {
        mHandler.post(mTaskUpdateTime);
    }

    private void stopTime() {
        mHandler.removeCallbacks(mTaskUpdateTime);
    }

    @Override
    public void clipLeftSliderChange(long duration, long cutStartTime, long cutEndTime, long originTrimIn, long originTrimOut) {
        tailorStartTime = cutStartTime;
        tailorEndTime = cutEndTime;
        cutVideo();
    }

    @Override
    public void clipRightSliderChange(long duration, long cutStartTime, long cutEndTime, long originTrimIn, long originTrimOut) {
        tailorStartTime = cutStartTime;
        tailorEndTime = cutEndTime;
        cutVideo();
    }

    @Override
    public void cropFirstLeftSliderChange(long duration, long cutStartTime, long cutEndTime, long originTrimIn, long originTrimOut) {

    }

    @Override
    public void cropFirstRightSliderChange(long duration, long cutStartTime, long cutEndTime, long originTrimIn, long originTrimOut) {

    }

    @Override
    public void cropSecondLeftSliderChange(long duration, long cutStartTime, long cutEndTime, long originTrimIn, long originTrimOut) {

    }

    @Override
    public void cropSecondRightSliderChange(long duration, long cutStartTime, long cutEndTime, long originTrimIn, long originTrimOut) {

    }

    @Override
    public void splitFirstSliderChange(long duration, long cutStartTime, long cutEndTime, long originTrimIn, long originTrimOut) {

    }

    @Override
    public void splitSecondSliderChange(long duration, long cutStartTime, long cutEndTime, long originTrimIn, long originTrimOut) {

    }
}